package pers.supeijin.devtools.converter.base;

import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiManager;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import pers.supeijin.devtools.converter.entity.OnConverterListener;
import pers.supeijin.devtools.utils.GeneralContext;

/**
 * @author supeijin
 */

public abstract class AbsConverterHelper<T extends OnConverterListener> {
	protected Project mProject;
	protected VirtualFile mSelectedVirtualFile;
	protected PsiDirectory mPsiDirectory;
	protected GeneralContext mGeneralContext;

	public AbsConverterHelper(GeneralContext context, VirtualFile selectedVirtualFile) {
		mGeneralContext = context;
		mProject = context.getProject();
		mPsiDirectory = PsiManager.getInstance(context.getProject()).findDirectory(context.getVirtualFile());
		mSelectedVirtualFile = selectedVirtualFile;
		HashMap<String, T> converterMap = getConverterMap(selectedVirtualFile);
		List<T> enableList = getEnableList(converterMap);
		if (enableList.size() == 0) {
			Messages.showInfoMessage("选中目录没有符合的转换文件", "提示");
		} else {
			//开始转换文件信息
			WriteCommandAction.runWriteCommandAction(context.getProject(), () -> transformVirtualFile(enableList));
		}
	}

	private HashMap<String, T> getConverterMap(VirtualFile virtualFile) {
		HashMap<String, T> map = new HashMap<String, T>();
		if (virtualFile != null && virtualFile.isDirectory()) {
			VirtualFile[] virtualFiles = virtualFile.getChildren();
			for (VirtualFile file : virtualFiles) {
				if (file.isDirectory()) {
					HashMap<String, T> converterMap = getConverterMap(file);
					if (converterMap.size() > 0) {
						map.putAll(converterMap);
					}
				} else {
					String nameWithoutExtension = file.getNameWithoutExtension();
					T converterItem = map.getOrDefault(nameWithoutExtension, null);
					if (converterItem == null) {
						converterItem = getConverterItem(nameWithoutExtension);
						map.put(nameWithoutExtension, converterItem);
					}
					converterItem.updateVirtualFile(file);
				}
			}
		}
		return map;
	}

	private List<T> getEnableList(HashMap<String, T> map) {
		return map.entrySet()
				.stream()
				.filter(entry -> entry.getValue().isEnable())
				.map(entry -> entry.getValue())
				.collect(Collectors.toList());
	}

	public abstract T getConverterItem(String fileNameWithoutExtension);

	public abstract void transformVirtualFile(List<T> map);
}
